/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

// 网点公众号管理

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import ProForm, { DrawerForm, ProFormText } from '@ant-design/pro-form';
import { Button, Space } from 'antd';
import KbPopconfirm from '@/components/KbPopconfirm';
import { getAccountsList } from '@/services/networkWxmini';
import { useLocation, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { MouseEvent } from 'react';
import type { Location } from 'umi';
import styles from '../index.less';

const NetworkWx: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const { query: urlParams } = useLocation() as Location;
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [isEdit, setIsEdit] = useState(false);

  const tableReload = () => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (!reset) return;
    reset();
  };

  const confirm = (params: any) => {
    const { id, platform } = params;
    getAccountsList({ action: 'delAdInfo', id, platform }).then(() => tableReload());
  };

  const onDrawer = async (cb: MouseEvent | (() => void)) => {
    const isFunction = typeof cb === 'function';
    setIsEdit(isFunction);
    formRef.current?.setFieldsValue({ name: '', ad_id: '' });
    await setDrawerVisit(true);
    if (!isFunction) return;
    cb();
  };

  const editAdInfo = (params: any) => {
    onDrawer(() => {
      getAccountsList({ action: 'getAdInfo', id: params.id, ...urlParams }).then((data) => {
        formRef.current?.setFieldsValue(data);
      });
    });
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      search: false,
    },
    {
      title: 'platform',
      dataIndex: 'platform',
      align: 'center',
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      align: 'center',
      search: false,
    },
    {
      title: 'ad_id',
      dataIndex: 'ad_id',
      align: 'center',
      search: false,
    },
    {
      title: '添加时间',
      dataIndex: 'create_time',
      align: 'center',
      search: false,
    },
    {
      title: '添加时间',
      dataIndex: 'create_time',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      dataIndex: 'option',
      fixed: 'right',
      width: winSize === 'xs' ? 50 : 100,
      render: (_, record: any) => {
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a onClick={() => editAdInfo(record)}>编辑</a>
            <KbPopconfirm
              text='你确定删除广告位吗'
              confirm={() => confirm(record)}
              cancel={() => {}}
              okText='确定'
              cancelText='取消'
              key={record.id}
            >
              <a>删除</a>
            </KbPopconfirm>
          </Space>
        );
      },
    },
  ];

  const fetchTableList = (params: any) => {
    const { current: page } = params;
    return getAccountsList({
      action: 'getAdInfoList',
      page_num: page,
      page_size: 20,
      ...urlParams,
    });
  };

  const onSubmit = async () => {
    window.history.back();
  };

  const add = async (values: any) => {
    getAccountsList({ action: 'addAdInfo', ...values, ...urlParams }).then(() => {
      setDrawerVisit(false);
      tableReload();
    });
  };

  return (
    <PageContainer className={styles.main} title=''>
      <ProForm
        layout='inline'
        onFinish={onSubmit}
        submitter={{
          render: (props) => {
            return [
              <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                返回
              </Button>,
              <Button type='primary' key='submit' onClick={onDrawer}>
                添加广告位
              </Button>,
            ];
          },
        }}
      />
      <DrawerForm
        title='广告位编辑'
        visible={drawerVisit}
        formRef={formRef}
        onVisibleChange={setDrawerVisit}
        onFinish={add}
        width={winSize === 'xs' ? 300 : 800}
      >
        <ProFormText
          name='name'
          width='md'
          label='名称'
          placeholder='name'
          rules={[{ required: true, message: '名称为必填' }]}
        />
        <ProFormText
          name='ad_id'
          width='md'
          label='AD_ID'
          disabled={isEdit}
          placeholder='ad_id'
          rules={[{ required: true, message: 'AD_ID为必填' }]}
        />
      </DrawerForm>
      <DragTable>
        <ProTable
          className='kb-pro-table'
          actionRef={actionRef}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          rowKey='id'
          request={fetchTableList}
          columns={columns}
          search={false}
          options={false}
          scroll={{ x: 1200 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default NetworkWx;
